from loguru import logger
from tybase.tools.image_utils import crop_image_from_url
from tybase.tools.image_utils import url_to_md5
import os
from PIL import Image
import subprocess


# 这个应该封装到tybase里,还比较常用,对图片进行裁剪
def process_user_image(url: str, user_images_name: str, max_dimension: int = 350, force_update: bool = False):
    """
    处理用户图片的函数。首先会尝试计算图片的md5值，然后判断本地是否已存在此图片，如果存在则直接返回本地路径。
    如果本地不存在此图片，或者设置了强制更新，则会下载图片，重新调整大小并保存到本地，然后返回新图片的本地路径。
    :param url: 用户图片的url
    :param user_images_name: 本地图片存储的目录
    :param max_dimension: 重新调整图片大小的最大维度
    :param force_update: 是否强制更新本地图片
    :return: 本地图片的路径
    """
    # 计算图片的md5值
    filename = url_to_md5(url)
    file_loc_path = os.path.join(user_images_name, filename)

    # 检查本地是否已存在此图片
    if os.path.isfile(file_loc_path) and not force_update:
        logger.debug(f"本地已存在用户图片 {file_loc_path}")
        return file_loc_path
    
    from tybase.tools.image_utils import read_image
    import cv2
    img = read_image(url)
    cv2.imwrite(file_loc_path, img)
    return file_loc_path


def get_image_resolution(image_file_path):
    # 返回图像的大小
    with Image.open(image_file_path) as img:
        return img.width, img.height


import math


def get_font_size_from_area(width, height, ratio=20):
    area = width * height
    return int(math.sqrt(area) / ratio)

# 给图片加水印
def add_watermark_to_image(image_file_path, watermark_text, fontfile_path=None, font_size_ratio=70, font_color="white",
                           position="bottom-right"):
    script_dir = os.path.dirname(os.path.realpath(__file__))
    
    # from utils.image_utils import add_watermark_to_image
    # font_size_ratio 往上加,字越小
    import shutil
    # 如果未提供字体文件路径，则使用默认字体文件路径
    if fontfile_path is None:
        fontfile_path = os.path.join(script_dir, '..', 'resources', 'LXGWHeartSerifCHS.ttf')

    width, height = get_image_resolution(image_file_path)
    # width, height = get_font_size_from_area(image_file_path)
    font_size = get_font_size_from_area(width, height, font_size_ratio)

    # 根据位置参数设置坐标
    x, y = (0, 0)  # 默认坐标
    if position == "bottom-center":
        x, y = "(w-text_w)/2", "h-text_h-0.02*h"  # 水平居中，垂直位于底部
    elif position == "top-left":
        x, y = "0.01*w", "0.02*h"  # 左上角
    elif position == "top-right":
        x, y = "w-text_w-0.01*w", "0.02*h"  # 右上角
    elif position == "bottom-left":
        x, y = "0.01*w", "h-text_h-0.02*h"  # 左下角
    elif position == "bottom-right":
        x, y = "w-text_w-0.01*w", "h-text_h-0.02*h"  # 右下角
        logger.debug(f"当前的位置是: {position}")
    else:
        x, y = "w-text_w-0.01*w", "h-text_h-0.02*h"  # 右下角
        

    # 使用subprocess.run来运行ffmpeg命令,这里必须要要用到ffmpeg吗?
    file_name_obj = os.path.basename(image_file_path).split(".")[0]
    output_file_path = f"output_{file_name_obj}.png"
    shell_command = [
        "ffmpeg",
        "-i", image_file_path,
        "-vf",
        f'''drawtext=fontfile={fontfile_path}:text='{watermark_text}':fontsize={font_size}:fontcolor={font_color}:x={x}:y={y}''',
        output_file_path,
        "-y"
    ]

    result = subprocess.run(shell_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    if result.returncode != 0:
        print(f"添加水印时出错: {result.stderr.decode('utf-8')}")
        return

    # os.rename(output_file_path, image_file_path)
    shutil.move(output_file_path, image_file_path)
    print(f"{image_file_path} 已加水印.")






# 图片裁剪成目标统一的尺寸
def crop_to_aspect_ratio(image_path, target_width, target_height):
    with Image.open(image_path) as img:
        img_width, img_height = img.size
        aspect_ratio = target_width / target_height

        # Calculate the new image dimensions that maintain the aspect ratio
        if img_width / img_height < aspect_ratio:
            new_height = int(img_width / aspect_ratio)
            left, upper, right, lower = 0, (img_height - new_height) // 2, img_width, (img_height + new_height) // 2
        else:
            new_width = int(img_height * aspect_ratio)
            left, upper, right, lower = (img_width - new_width) // 2, 0, (img_width + new_width) // 2, img_height

        # Crop the image to the new dimensions
        img_cropped = img.crop((left, upper, right, lower))
        
        # Resize if cropped dimensions are not equal to target dimensions
        if (right - left, lower - upper) != (target_width, target_height):
            img_cropped = img_cropped.resize((target_width, target_height), Image.ANTIALIAS)
        return img_cropped


# 裁剪图片的主函数
def crop_image(image_path,target_width,target_height,output_path):
    # Crop the image
    cropped_image = crop_to_aspect_ratio(image_path, target_width, target_height)
    cropped_image.save(output_path)
    return output_path
    

    
# 把图片进行裁剪成统一尺寸
def crop_image_list(images_list):
    # 打开图片
    img = Image.open(images_list[0])
    # 获取图片的宽和高
    width, height = img.size

    for image_path in images_list[1:]:
        crop_image(image_path,width, height,image_path)



if __name__ == '__main__':
    print(crop_image_from_url(
        url='https://ty-huanlian.oss-cn-shanghai.aliyuncs.com/face_replace/20230712/74011b30c0cd50cd4a7dd1fa29a6368f.png',
        save_path="./1.png", max_dimension=350))
